<?php

require_once(WSB_MODULES_PATH . 'sherpa/models/AddressGateway.php');
require_once(WSB_MODULES_PATH . 'sherpa/forms/Address.php');

class Sherpa_AddressBookController extends WSB_Xtension_Extension
{

	/**
	 * @return string
	 */
	public function renderForBackend()
	{
		return get_class($this);
	}

	/**
	 * Initialisierung
	 */
	public function init()
	{
		$this->initTranslate();
	}

	/**
	 * Index Action
	 */
	public function indexAction()
	{
		$gateway = new Sherpa_Model_AddressGateway();
		$addresses = $gateway->fetchAddresses();
		$this->assignToView('addresses', $addresses);
		$this->renderView('addressbook/index.phtml');
	}

	/**
	 * Form Action
	 *
	 * @param Sherpa_Form_Address $form
	 */
	public function formAction(Sherpa_Form_Address $form = null)
	{
		if(is_null($form)) {
			$form = new Sherpa_Form_Address();
		}
		$id = intval($this->getParam('id', 0));
		if($id > 0) {
			$request = $this->getRequest();
			$gateway = new Sherpa_Model_AddressGateway();
			$address = $gateway->fetchAddress($id);
			$form->setDefaults(array_merge($address->toArray(), $request->getPost()));
		}
		$form->getElement('btnCreateAddress')->setLabel('sherpaButtonSaveAddress');
		$this->assignToView('id', $id);
		$this->assignToView('form', $form);
		$this->renderView('addressbook/form.phtml');
	}

	/**
	 * Save Action
	 */
	public function saveAction()
	{
		$request = $this->getRequest();
		$form = new Sherpa_Form_Address();
		if($request->isPost() && $form->isValid($request->getPost())) {
			$gateway = new Sherpa_Model_AddressGateway();
			$id = intval($this->getParam('id', 0));
			if($id > 0) {
				$gateway->updateAddress($form->getValues(), $id);
			} else {
				$gateway->addAddress($form->getValues());
			}
			$this->indexAction();
		} else {
			$this->formAction($form);
		}
	}

	/**
	 * Delete Action
	 */
	public function deleteAction()
	{
		$id = intval($this->getParam('id', 0));
		$confirmed = trim($this->getParam('confirmed'));
		$gateway = new Sherpa_Model_AddressGateway();
		if(($id > 0) && ($confirmed != '')) {
			$gateway->deleteAddress($id);
			$this->indexAction();
		} elseif($id > 0) {
			$this->assignToView('id', $id);
			$this->assignToView('address', $gateway->fetchAddress($id));
			$this->renderView('addressbook/delete.phtml');
		}
	}

}